import React from 'react';
import { Card, Table, Typography, Space, Tag, Empty, Divider } from 'antd';
import { CheckCircleOutlined, CloseCircleOutlined } from '@ant-design/icons';
import { useProduct } from '../context/ProductContext';
import { Product } from '../types';

const { Title, Text } = Typography;

const ProductComparison: React.FC = () => {
  const { state } = useProduct();
  const { selectedProducts } = state;

  // 如果没有选择产品，显示空状态
  if (selectedProducts.length === 0) {
    return (
      <Card style={{ margin: '24px' }}>
        <Empty
          description="请选择产品进行比较"
          image={Empty.PRESENTED_IMAGE_SIMPLE}
        />
      </Card>
    );
  }

  // 如果只选择了一个产品，显示单个产品的详细信息
  if (selectedProducts.length === 1) {
    const product = selectedProducts[0];
    
    return (
      <Card 
        style={{ margin: '24px' }}
        title={
          <Space>
            <Title level={3} style={{ margin: 0 }}>
              {product.name}
            </Title>
            <Tag color="blue">{product.category}</Tag>
            <Tag color="green">{product.subcategory}</Tag>
          </Space>
        }
      >
        <div style={{ padding: '16px 0' }}>
          <Title level={4}>产品参数</Title>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(300px, 1fr))', gap: '16px' }}>
            {Object.entries(product.specs).map(([key, value]) => (
              <div key={key} style={{ 
                padding: '12px', 
                backgroundColor: '#fafafa', 
                borderRadius: '6px',
                border: '1px solid #f0f0f0'
              }}>
                <Text strong style={{ display: 'block', marginBottom: '4px' }}>
                  {key}
                </Text>
                <Text>{String(value)}</Text>
              </div>
            ))}
          </div>
        </div>
      </Card>
    );
  }

  // 确保选择了两个不同的产品
  if (selectedProducts.length !== 2) {
    return (
      <Card style={{ margin: '24px' }}>
        <Empty
          description={
            <div>
              <p>请选择两个产品进行比较</p>
              <p style={{ color: '#666', fontSize: '14px' }}>
                当前已选择: {selectedProducts.length}/2
              </p>
            </div>
          }
          image={Empty.PRESENTED_IMAGE_SIMPLE}
        />
      </Card>
    );
  }

  // 两个产品的对比
  const [product1, product2] = selectedProducts;
  
  // 检查是否是不同的产品
  const areDifferentProducts = product1.id !== product2.id;
  
  if (!areDifferentProducts) {
    return (
      <Card style={{ margin: '24px' }}>
        <Empty
          description="请选择两个不同的产品进行比较"
          image={Empty.PRESENTED_IMAGE_SIMPLE}
        />
      </Card>
    );
  }

  // 获取所有参数的并集
  const allSpecs = new Set([
    ...Object.keys(product1.specs),
    ...Object.keys(product2.specs)
  ]);

  // 构建对比数据
  const comparisonData = Array.from(allSpecs).map(spec => {
    const value1 = product1.specs[spec];
    const value2 = product2.specs[spec];
    
    // 处理图片对象的比较
    const getValue = (value: any) => {
      if (typeof value === 'object' && value !== null && 'image' in value) {
        return value.value || '';
      }
      return value !== undefined ? String(value).trim() : '';
    };
    
    const str1 = getValue(value1);
    const str2 = getValue(value2);
    
    // 如果两个值都存在且不相同，则标记为不同
    const isDifferent = (str1 !== '' && str2 !== '' && str1 !== str2) || 
                       (str1 === '' && str2 !== '') || 
                       (str1 !== '' && str2 === '');
    
    // 详细调试信息
    console.log(`参数: ${spec}`);
    console.log(`  产品1 "${product1.name}": "${str1}" (原值: ${typeof value1}, ${JSON.stringify(value1)})`);
    console.log(`  产品2 "${product2.name}": "${str2}" (原值: ${typeof value2}, ${JSON.stringify(value2)})`);
    console.log(`  是否不同: ${isDifferent}`);
    console.log('---');
    
    return {
      key: spec,
      spec,
      product1: value1, // 保持原始值，包括图片对象
      product2: value2, // 保持原始值，包括图片对象
      isDifferent,
      hasValue1: value1 !== undefined,
      hasValue2: value2 !== undefined,
    };
  });
  
  console.log('对比数据:', comparisonData);
  console.log('不同参数数量:', comparisonData.filter(item => item.isDifferent).length);

  // 表格列定义
  const columns = [
    {
      title: '参数',
      dataIndex: 'spec',
      key: 'spec',
      width: '30%',
      align: 'center' as const,
      render: (text: string, record: any) => (
        <Text strong style={{ 
          color: record.isDifferent ? '#ff4d4f' : '#000000',
          fontWeight: record.isDifferent ? 'bold' : '500'
        }}>
          {text}
        </Text>
      ),
    },
    {
      title: (
        <div style={{ textAlign: 'center' }}>
          <Space direction="vertical" size="small">
            <Text strong>{product1.name}</Text>
            <Tag color="blue">{product1.category}</Tag>
          </Space>
        </div>
      ),
      dataIndex: 'product1',
      key: 'product1',
      width: '35%',
      align: 'center' as const,
      render: (text: string, record: any) => (
        <div style={{
          padding: '8px',
          backgroundColor: record.isDifferent ? '#ffebee' : '#f6ffed',
          borderRadius: '4px',
          border: `3px solid ${record.isDifferent ? '#f44336' : '#b7eb8f'}`,
          position: 'relative',
          boxShadow: record.isDifferent ? '0 2px 8px rgba(244, 67, 54, 0.2)' : 'none'
        }}>
          {!record.hasValue1 && (
            <CloseCircleOutlined style={{ color: '#ff4d4f', marginRight: '4px' }} />
          )}
          {record.hasValue1 && record.isDifferent && (
            <CheckCircleOutlined style={{ color: '#52c41a', marginRight: '4px' }} />
          )}
          <Text style={{ 
            color: record.isDifferent ? '#d32f2f' : '#000000',
            fontWeight: record.isDifferent ? 'bold' : 'normal',
            fontSize: record.isDifferent ? '14px' : '13px',
            textShadow: record.isDifferent ? '0 1px 2px rgba(0,0,0,0.1)' : 'none'
          }}>
            {/* 检查是否包含图片 */}
            {(() => {
              const cellValue = record.product1;
              console.log('🔍 检查product1值:', cellValue);
              
              // 如果没有值，显示 '-'
              if (cellValue === undefined || cellValue === null || cellValue === '') {
                return '-';
              }
              
              // 安全的图片对象检测
              const isImageObject = typeof cellValue === 'object' && 
                                   cellValue !== null && 
                                   cellValue.hasOwnProperty('image') &&
                                   cellValue.hasOwnProperty('value') &&
                                   cellValue.image && 
                                   typeof cellValue.image === 'string' &&
                                   cellValue.image.startsWith('data:image');
              
              if (isImageObject) {
                console.log('🖼️ ✅ Product1检测到图片对象:', cellValue);
                return (
                  <div style={{ textAlign: 'center' }}>
                    <div style={{ marginBottom: '8px', fontSize: '14px' }}>
                      {cellValue.value || ''}
                    </div>
                    <img 
                      src={cellValue.image} 
                      alt={cellValue.value || '产品图片'}
                      style={{ 
                        maxWidth: '120px', 
                        maxHeight: '120px',
                        objectFit: 'contain',
                        border: '2px solid #d9d9d9',
                        borderRadius: '6px',
                        backgroundColor: '#f9f9f9'
                      }}
                      onError={(e) => {
                        console.error('❌ Product1图片加载失败:', cellValue.image);
                        e.currentTarget.style.display = 'none';
                      }}
                      onLoad={() => {
                        console.log('✅ Product1图片加载成功!');
                      }}
                    />
                  </div>
                );
              }
              
              // 如果是对象类型但不是图片对象，显示调试信息
              if (typeof cellValue === 'object' && cellValue !== null) {
                console.log('🔍 Product1是对象类型:', cellValue);
                return (
                  <div style={{ textAlign: 'center' }}>
                    <div style={{ marginBottom: '8px', fontSize: '10px', color: '#666' }}>
                      <strong>🔍 Product1 对象调试:</strong>
                    </div>
                    <pre style={{ 
                      fontSize: '9px', 
                      textAlign: 'left', 
                      margin: '4px 0',
                      backgroundColor: '#f5f5f5',
                      padding: '4px',
                      borderRadius: '2px',
                      overflow: 'auto',
                      maxHeight: '80px',
                      maxWidth: '200px'
                    }}>
                      {JSON.stringify(cellValue, null, 1)}
                    </pre>
                    <div style={{ fontSize: '10px', textAlign: 'left' }}>
                      <strong>类型:</strong> {typeof cellValue}<br/>
                      <strong>构造函数:</strong> {cellValue.constructor ? cellValue.constructor.name : 'N/A'}<br/>
                      <strong>属性:</strong> {Object.keys(cellValue).join(', ') || '无'}<br/>
                      {Object.keys(cellValue).includes('image') && <><strong>✅ 有image!</strong><br/></>}
                      {Object.keys(cellValue).includes('value') && <><strong>✅ 有value!</strong><br/></>}
                    </div>
                  </div>
                );
              }
              
              // 普通文本值
              return String(cellValue);
            })()}
          </Text>
        </div>
      ),
    },
    {
      title: (
        <div style={{ textAlign: 'center' }}>
          <Space direction="vertical" size="small">
            <Text strong>{product2.name}</Text>
            <Tag color="green">{product2.category}</Tag>
          </Space>
        </div>
      ),
      dataIndex: 'product2',
      key: 'product2',
      width: '35%',
      align: 'center' as const,
      render: (text: string, record: any) => (
        <div style={{
          padding: '8px',
          backgroundColor: record.isDifferent ? '#ffebee' : '#f6ffed',
          borderRadius: '4px',
          border: `3px solid ${record.isDifferent ? '#f44336' : '#b7eb8f'}`,
          position: 'relative',
          boxShadow: record.isDifferent ? '0 2px 8px rgba(244, 67, 54, 0.2)' : 'none'
        }}>
          {!record.hasValue2 && (
            <CloseCircleOutlined style={{ color: '#ff4d4f', marginRight: '4px' }} />
          )}
          {record.hasValue2 && record.isDifferent && (
            <CheckCircleOutlined style={{ color: '#52c41a', marginRight: '4px' }} />
          )}
          <Text style={{ 
            color: record.isDifferent ? '#d32f2f' : '#000000',
            fontWeight: record.isDifferent ? 'bold' : 'normal',
            fontSize: record.isDifferent ? '14px' : '13px',
            textShadow: record.isDifferent ? '0 1px 2px rgba(0,0,0,0.1)' : 'none'
          }}>
            {/* 检查是否包含图片 */}
            {(() => {
              const cellValue = record.product2;
              console.log('🔍 检查product2值:', cellValue);
              
              // 如果没有值，显示 '-'
              if (cellValue === undefined || cellValue === null || cellValue === '') {
                return '-';
              }
              
              // 安全的图片对象检测
              const isImageObject = typeof cellValue === 'object' && 
                                   cellValue !== null && 
                                   cellValue.hasOwnProperty('image') &&
                                   cellValue.hasOwnProperty('value') &&
                                   cellValue.image && 
                                   typeof cellValue.image === 'string' &&
                                   cellValue.image.startsWith('data:image');
              
              if (isImageObject) {
                console.log('🖼️ ✅ Product2检测到图片对象:', cellValue);
                return (
                  <div style={{ textAlign: 'center' }}>
                    <div style={{ marginBottom: '8px', fontSize: '14px' }}>
                      {cellValue.value || ''}
                    </div>
                    <img 
                      src={cellValue.image} 
                      alt={cellValue.value || '产品图片'}
                      style={{ 
                        maxWidth: '120px', 
                        maxHeight: '120px',
                        objectFit: 'contain',
                        border: '2px solid #d9d9d9',
                        borderRadius: '6px',
                        backgroundColor: '#f9f9f9'
                      }}
                      onError={(e) => {
                        console.error('❌ Product2图片加载失败:', cellValue.image);
                        e.currentTarget.style.display = 'none';
                      }}
                      onLoad={() => {
                        console.log('✅ Product2图片加载成功!');
                      }}
                    />
                  </div>
                );
              }
              
              // 如果是对象类型但不是图片对象，显示调试信息
              if (typeof cellValue === 'object' && cellValue !== null) {
                console.log('🔍 Product2是对象类型:', cellValue);
                return (
                  <div style={{ textAlign: 'center' }}>
                    <div style={{ marginBottom: '8px', fontSize: '10px', color: '#666' }}>
                      <strong>🔍 Product2 对象调试:</strong>
                    </div>
                    <pre style={{ 
                      fontSize: '9px', 
                      textAlign: 'left', 
                      margin: '4px 0',
                      backgroundColor: '#f5f5f5',
                      padding: '4px',
                      borderRadius: '2px',
                      overflow: 'auto',
                      maxHeight: '80px',
                      maxWidth: '200px'
                    }}>
                      {JSON.stringify(cellValue, null, 1)}
                    </pre>
                    <div style={{ fontSize: '10px', textAlign: 'left' }}>
                      <strong>类型:</strong> {typeof cellValue}<br/>
                      <strong>构造函数:</strong> {cellValue.constructor ? cellValue.constructor.name : 'N/A'}<br/>
                      <strong>属性:</strong> {Object.keys(cellValue).join(', ') || '无'}<br/>
                      {Object.keys(cellValue).includes('image') && <><strong>✅ 有image!</strong><br/></>}
                      {Object.keys(cellValue).includes('value') && <><strong>✅ 有value!</strong><br/></>}
                    </div>
                  </div>
                );
              }
              
              // 普通文本值
              return String(cellValue);
            })()}
          </Text>
        </div>
      ),
    },
  ];

  // 统计信息
  const differentCount = comparisonData.filter(item => item.isDifferent).length;
  const sameCount = comparisonData.length - differentCount;
  const onlyProduct1Count = comparisonData.filter(item => item.hasValue1 && !item.hasValue2).length;
  const onlyProduct2Count = comparisonData.filter(item => !item.hasValue1 && item.hasValue2).length;

  return (
    <div style={{ margin: '24px' }}>
      {/* 对比标题 */}
      <Card style={{ marginBottom: '16px' }}>
        <div style={{ textAlign: 'center' }}>
          <Title level={2} style={{ margin: 0 }}>
            产品参数对比
          </Title>
          <Space size="large" style={{ marginTop: '16px' }}>
            <div>
              <Text strong style={{ fontSize: '18px', color: '#1890ff' }}>
                {product1.name}
              </Text>
              <br />
              <Text type="secondary">{product1.category} - {product1.subcategory}</Text>
            </div>
            <Divider type="vertical" style={{ height: '40px' }} />
            <Text strong style={{ fontSize: '24px', color: '#722ed1' }}>VS</Text>
            <Divider type="vertical" style={{ height: '40px' }} />
            <div>
              <Text strong style={{ fontSize: '18px', color: '#52c41a' }}>
                {product2.name}
              </Text>
              <br />
              <Text type="secondary">{product2.category} - {product2.subcategory}</Text>
            </div>
          </Space>
        </div>
      </Card>

      {/* 统计信息 */}
      <Card style={{ marginBottom: '16px' }}>
        <Space size="large">
          <div>
            <Text type="secondary">总参数数量</Text>
            <br />
            <Text strong style={{ fontSize: '20px', color: '#1890ff' }}>
              {comparisonData.length}
            </Text>
          </div>
          <div>
            <Text type="secondary">相同参数</Text>
            <br />
            <Text strong style={{ fontSize: '20px', color: '#52c41a' }}>
              {sameCount}
            </Text>
          </div>
          <div>
            <Text type="secondary">不同参数</Text>
            <br />
            <Text strong style={{ fontSize: '20px', color: '#ff4d4f' }}>
              {differentCount}
            </Text>
          </div>
          <div>
            <Text type="secondary">仅{product1.name}有</Text>
            <br />
            <Text strong style={{ fontSize: '20px', color: '#722ed1' }}>
              {onlyProduct1Count}
            </Text>
          </div>
          <div>
            <Text type="secondary">仅{product2.name}有</Text>
            <br />
            <Text strong style={{ fontSize: '20px', color: '#eb2f96' }}>
              {onlyProduct2Count}
            </Text>
          </div>
        </Space>
      </Card>

      {/* 对比表格 */}
      <Card title="详细参数对比">
        <Table
          columns={columns}
          dataSource={comparisonData}
          pagination={false}
          size="middle"
          scroll={{ y: 600 }}
          className="centered-table-header"
        />
      </Card>
    </div>
  );
};

export default ProductComparison; 